package com.uhylab.uhuvinetest.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.adapter.BleDeviceListAdapter;
import com.uhylab.uhuvinetest.utils.Utils;

public class UHScanDeviceActivity extends Activity implements View.OnClickListener {
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    ListView listView;
    SwipeRefreshLayout swagLayout;
    BluetoothAdapter mBluetoothAdapter;
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    BleDeviceListAdapter mBleDeviceListAdapter;
    boolean isExit;
    Handler handler;
    private ImageView iv_back;
    private boolean isCan = true;

    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    private static final int REQUEST_ENABLE_BT = 1;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient mClient;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uhscan_device);
        //getActionBar().setTitle(R.string.app_title);

        // Use this check to determine whether BLE is supported on the device.  Then you can
        // selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        try {
            final BluetoothManager bluetoothManager =
                    (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            mBluetoothAdapter = bluetoothManager.getAdapter();
        } catch (NoClassDefFoundError noClassDefFoundError) {
            isCan = false;
            Toast.makeText(this, "该设备不支持", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            isCan = false;
            Toast.makeText(this, "该设备不支持", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        sharedPreferences = getPreferences(0);
        editor = sharedPreferences.edit();
        init();
        getBleAdapter();
        getScanResualt();
//        new Thread(new Runnable() {
//            @SuppressWarnings("deprecation")
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                mBluetoothAdapter.startLeScan(mLeScanCallback);
//            }
//        }).start();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        mClient = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void init() {
        // TODO Auto-generated method stub
        listView = (ListView) findViewById(R.id.lv_deviceList);
        listView.setEmptyView(findViewById(R.id.pb_empty));
        swagLayout = (SwipeRefreshLayout) findViewById(R.id.swagLayout);
        swagLayout.setVisibility(View.VISIBLE);
        swagLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onRefresh() {
                // TODO Auto-generated method stub
                mBleDeviceListAdapter.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
                swagLayout.setRefreshing(false);
            }
        });
        mBleDeviceListAdapter = new BleDeviceListAdapter(this);
        listView.setAdapter(mBleDeviceListAdapter);
        setListItemListener();

        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
    }

    @SuppressLint("NewApi")
    private void getBleAdapter() {
        final BluetoothManager bluetoothManager = (BluetoothManager) this
                .getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        if (mBluetoothAdapter.isEnabled()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("This app needs location access");
                    builder.setMessage("Please grant location access so this app can detect Bluetooth.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                            }
                        }
                    });
                    builder.show();
                }
            }
        }
    }

    /*
    *对授权做处理，0代表授权，-1拒绝授权
    */
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {

        switch (requestCode) {
            case PERMISSION_REQUEST_COARSE_LOCATION: {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // Log.d(TAG, "coarse location permission granted");
                    finish();
                } else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since location access has not been granted,</span> this app will not be able to discover beacons when in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }
                return;
            }
        }
    }

    @SuppressLint("NewApi")
    private void getScanResualt() {
        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, final int rssi,
                                 final byte[] scanRecord) {
                Log.e("TAG", "zhaodao ygie ");
                UHScanDeviceActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        mBleDeviceListAdapter.addDevice(device, rssi,
                                Utils.bytesToHex(scanRecord));
                        mBleDeviceListAdapter.notifyDataSetChanged();
                        invalidateOptionsMenu();
                    }
                });
            }
        };
    }

    private void setListItemListener() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                BluetoothDevice device = mBleDeviceListAdapter
                        .getDevice(position);
                final Intent intent = new Intent(UHScanDeviceActivity.this,
                        UHDeviceControlActivity.class);
                intent.putExtra(UHDeviceControlActivity.EXTRAS_DEVICE_NAME,
                        device.getName());
                intent.putExtra(UHDeviceControlActivity.EXTRAS_DEVICE_ADDRESS,
                        device.getAddress());
                startActivity(intent);
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }

        // Initializes list view adapter.
        getBleAdapter();
        getScanResualt();
        new Thread(new Runnable() {
            @SuppressWarnings("deprecation")
            @Override
            public void run() {
                // TODO Auto-generated method stub
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            }
        }).start();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (isCan) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            mBleDeviceListAdapter.clear();
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main2, menu);
        menu.getItem(0).setTitle("共" + mBleDeviceListAdapter.getCount() + "个");
        return true;
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_stop:
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                break;
            case R.id.menu_autoconnect:
                if (sharedPreferences.getBoolean("AutoConnect", true)) {
                    editor.putBoolean("AutoConnect", false);
                    editor.commit();
                    Toast.makeText(this, "取消自动连接", Toast.LENGTH_SHORT).show();
                } else {
                    editor.putBoolean("AutoConnect", true);
                    editor.commit();
                    Toast.makeText(this, "已设置为断开后自动连接", Toast.LENGTH_SHORT).show();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }



}